<?php

namespace App\HttpController\Applet\Apang;

use App\Model\WechatsModel;
use App\Utility\Cache;
use App\Utility\CacheDatas;
use App\Utility\Music;
use Carbon\Carbon;

/**
 * @description 美文控制器
 */
class IndexController extends AuthController {
    //列表
    public function index(){
        $request = $this->request();
        $params = $request->getRequestParam();
        $isHot = $request->getRequestParam('hot')??0;
        $appletModel = $this->appletArticleModel($this->applet);
        $cache = new CacheDatas();
        $cacheName = 'datas-'.$this->applet.'-isHot-'.(string)$isHot;
        if(empty($cache->has($cacheName))){
            $model = new $appletModel;
            $list = $model->select('id,thumb,title,is_link,link_url')
                ->where(function ($query) use($params){
                    if(isset($params['hot']) && $params['hot']) $query->where('hot',$params['hot']);
                })
                ->where('status',1)
                ->get();
            $cache->sAddBatch($cacheName,$list,$this->cacheTime);
            unset($model);
        }
        $lists = $cache->sRandBatch($cacheName,40);
        unset($cache);
        return $this->writeJson(0,$lists);
    }
    //详情
    public function info(){
        $request = $this->request();
        $id = $request->getRequestParam('id') ??  0;
        $share = $request->getRequestParam('share') ?? null;
        $openid = $request->getRequestParam('openid') ?? '';
        if(empty($id)){
            return $this->writeJson(1,null,'参数不正确');
        }
        $cacheName = 'info-'.$this->applet.'-id-'.$id;
            $articlesTableName = 'articles_'.$this->applet;
            $columns = $articlesTableName.'.id,'
                .$articlesTableName.'.cateid,'
                .$articlesTableName.'.userid,'
                .$articlesTableName.'.title,'
                .$articlesTableName.'.title_color,'
                .$articlesTableName.'.thumb,'
                .$articlesTableName.'.music,'
                .$articlesTableName.'.created_at,'
                .$articlesTableName.'.is_link,'
                .$articlesTableName.'.link_url,'
                .$articlesTableName.'.content,'
                .$articlesTableName.'.backimg,categorys.name as username,categorys.thumb as avatar';
        $cache = new CacheDatas();
        if(empty($cache->has($cacheName))){
            $appletModel = $this->appletArticleModel($this->applet);
            $model = new $appletModel;
            $info = $model->select($columns)
                ->join('categorys', 'categorys.id = '.$articlesTableName.'.cateid','RIGHT')
                ->find($id);
            if(empty($info)){
                //数据不存在随机返回一条信息
                $info = $model->select($columns)
                ->join('categorys', 'categorys.id = '.$articlesTableName.'.cateid','RIGHT')->inRandomOrder()->first();
            }
            $cache->set($cacheName,$info,$this->cacheTime);
            unset($model);
        }
        $data = $cache->get($cacheName);
        unset($cache);
        $queueData = [
            'id' => $id,
            'admin_id' => $data['userid'],
            'share' => $share,
            'openid' => $openid,
            'applet' => $this->applet,
            'applet_type' => 'article',
        ];
        $data['music'] = (new Music())->getMusic($data['music']);
        //开启任务-创建统计自增推送队列
        $queue = new Cache();
        $queue->onQueue('count-inc');
        $queue->push($queueData);
        unset($queue);
        return $this->writeJson(0,$data);
    }

    //随机查询8条文章
    public function list(){
        $cacheName = 'datas-'.$this->applet.'-all';
        $cache = new CacheDatas();
        if(empty($cache->has($cacheName))){
            $appletArticleName = $this->appletArticleModel($this->applet);
            $model = new $appletArticleName;
            $list = $model->select('id,thumb,title,is_link,link_url')
                ->where('status',1)
                ->inRandomOrder()
            ->take(8)
                ->get();
            $cache->sAddBatch($cacheName,$list,$this->cacheTime);
            unset($model);
        }
        $lists = $cache->sRandBatch($cacheName,20);
        unset($cache);
        return $this->writeJson(0,$lists);
    }


    //收集模板消息的formid
    public function formId(){
        $request = $this->request();
        $openid = trim($request->getRequestParam('openid')) ?: '';
        $formid = trim($request->getRequestParam('formid')) ?: '';
        if($formid =='the formId is a mock one'){
            return $this->writeJson(1,null,'测试数据');
        }
        if(!$openid || !$formid){
            return $this->writeJson(1,null,'参数错误');
        }
        $queue = new Cache();
        $queue->onQueue('formid');
        $queue->push([
            'openid' => $openid,
            'expire' => Carbon::now()->addDays(7)->timestamp,
            'formid' => $formid,
            'name'   => $this->applet
        ]);
        unset($queue);
        return $this->writeJson(0);
    }

    public function config(){
        $request = $this->request();
        $name = trim($request->getRequestParam('name')) ?: '';
        if(!$name){
            return $this->writeJson(1,null,'参数不正确');
        }
        $cacheName = 'links-'.$this->applet.'-configs-'.$name;
        $cache = new CacheDatas();
        if(empty($cache->has($cacheName))){
            $appletVideoName = $this->appletConfigModel($this->applet);
            $model = new $appletVideoName;
            $info = $model->select('value')->where('name',$name)->first();
            $cache->set($cacheName,$info['value'],$this->cacheTime);
            unset($model);
        }
        $link = $cache->get($cacheName);
        unset($cache);
        return $this->writeJson(0,['value' => $link]);
    }
    /**
     * 获取公众号链接文章
     */
    public function wechatLink(){
        $request = $this->request();
        $position = $request->getRequestParam('position') ?? 1;
        $cache = new CacheDatas();
        $cacheName = 'wechat-'.$this->applet.'-position-'.$position;
        if(empty($cache->has($cacheName))){
            $appletModel = new WechatsModel();
            $list = $appletModel->where('position',$position)
                ->where('name',$this->applet)
                ->take(10)
                ->get();
            $cache->set($cacheName,$list,$this->cacheTime);
            unset($model);
        }
        $lists = $cache->get($cacheName);
        unset($cache);
        return $this->writeJson(0,$lists);
    }

    /**
     * 获取预约状态
     */
    public function reserve(){
        $request= $this->request();
        $params = $request->getRequestParam();
        if(!$params['openid']){
            return $this->writeJson(1,null,'参数不正确');
        }
        $userModelName = $this->appletUserModel($this->applet);
        $userModel = new $userModelName;
        $userInfo = $userModel->where('openid',$params['openid'])->first();

        return $this->writeJson(0,['status'=>$userInfo['status']],'ok');
    }

    /**
     * 更新预约状态
     */
    public function reserveUpdate(){
        $request= $this->request();
        $params = $request->getRequestParam();
        if(!$params['status']){
            $params['status'] = 1;
        }
        if(!$params['openid']){
            return $this->writeJson(1,null,'参数不正确');
        }
        $userModelName = $this->appletUserModel($this->applet);
        $userModel = new $userModelName;
        $userInfo = $userModel->where('openid',$params['openid'])->first();
        if($userInfo){
            if($userInfo['status'] == $params['status']){
                return $this->writeJson(0,null,'ok');
            }
            $userInfo['status'] = $params['status'];
            $isUpdate = $userModel->update($userInfo);
            if($isUpdate){
                return $this->writeJson(0,null,'ok');
            }
            return $this->writeJson(1,null,'error');
        }
        return $this->writeJson(1,null,'error:'.$params['openid']);

    }
}
